﻿using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;

namespace Microsoft.Media.IngestClient
{
    internal static class HttpWebRequestExtensions
    {
        public static async Task<HttpWebResponse> PostAsync(this HttpWebRequest request, Stream data, CancellationToken cancellationToken, IProgress<ulong> progress)
        {
            const int bufferSize = 64 * 1024;
            byte[] buffer = new byte[bufferSize];

            request.Method = "POST";
            ulong total = 0;
            using (var requestStream = await request.GetRequestStreamAsync())
            {
                cancellationToken.ThrowIfCancellationRequested();
                do
                {
                    int read = await data.ReadAsync(buffer, 0, buffer.Length, cancellationToken);
                    if (read <= 0) break;
                    await requestStream.WriteAsync(buffer, 0, read, cancellationToken);
                    total += (ulong)read;
                    progress.Report(total);
                } while (true);
            }

            return (HttpWebResponse)(await request.GetResponseAsync());
        }

    }
}
